package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.hmdp.utils.RedisConstants.FOLLOWS_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    IUserService userService;
//    tip 关注
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
//        获取登录用户
        Long userId = UserHolder.getUser().getId();
        String key = FOLLOWS_KEY+userId;
        if (userId==null)
        {
            return Result.fail("请先登录");
        }
//       判断是否关注
        if (BooleanUtil.isTrue(isFollow))
        {
//           如果是关注 进行数据库的填写 并加入数据到redis中
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            follow.setCreateTime(LocalDateTime.now());
            this.save(follow);

            Long followUser = stringRedisTemplate.opsForSet().add(key, followUserId.toString());

        }
        else
        {
//            取消关注 删数据库 删redis
            LambdaQueryWrapper<Follow> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Follow::getUserId,userId)
                    .eq(Follow::getFollowUserId,followUserId);
            this.remove(wrapper);


            stringRedisTemplate.opsForSet().remove(key,followUserId.toString());
        }
        return Result.ok();
    }

//    tip 取消关注
    @Override
    public Result isFollow(Long followUserId) {
        // 1.获取登录用户
        Long userId = UserHolder.getUser().getId();
        // 2.查询是否关注 select count(*) from tb_follow where user_id = ? and follow_user_id = ?
        Integer count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
        // 3.判断
        return Result.ok(count > 0);
    }

//    tip 实现共同关注
    @Override
    public Result commonFollow(Long followUserId) {
//        tip 用set命令的交集来进行实现
//        查询当前用户
        Long LoginUserId = UserHolder.getUser().getId();
//        创建两个key 用于查交集
        String keylogin =  FOLLOWS_KEY+LoginUserId;
        String keyStar =   FOLLOWS_KEY+followUserId;
//        用Redis中的set集合 查交集
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(keylogin, keyStar);
        if (intersect == null || intersect.isEmpty()) {
            // 无交集
            return Result.ok(Collections.emptyList());
        }
//        转为long类型的数组
        List<Long> list = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
//        将查出来的数组进行遍历 然后转为userDto
        List<UserDTO> allCommonFollowUser = userService.listByIds(list)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(allCommonFollowUser);
    }
}
